package cn.wolfcode.wolf2world.utils;

import cn.wolfcode.wolf2world.query.QueryObject;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

/**
 * @author 杨兴健
 * @Date 2020/8/12 10:14
 */
public class DBHelper {

    public static <T> Page<T> getPage(MongoTemplate mongoTemplate, Query query, QueryObject qo, Class<T> clz, Sort.Direction dir ,String sortField) {

        long count = mongoTemplate.count(query, clz);
        if (count == 0) {
            return Page.empty();
        }
        Pageable pageRequest = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(),dir, sortField);
        query.with(pageRequest);
        List<T> list = mongoTemplate.find(query, clz);
        return new PageImpl<T>(list, pageRequest, count);
    }
}
